package br.com.ufpr.sgp.pages.processo;

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

import javax.ejb.EJB;

import org.apache.wicket.AttributeModifier;
import org.apache.wicket.PageReference;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.extensions.ajax.markup.html.autocomplete.AutoCompleteTextField;
import org.apache.wicket.markup.html.form.DropDownChoice;
import org.apache.wicket.markup.html.form.TextArea;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.form.validation.IFormValidator;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.model.ResourceModel;
import org.apache.wicket.util.string.Strings;
import org.wicketstuff.annotation.mount.MountPath;

import br.com.sebrae.pr.sgp.entities.Cliente;
import br.com.sebrae.pr.sgp.entities.Processo;
import br.com.sebrae.pr.sgp.services.ClienteServiceRemote;
import br.com.sebrae.pr.sgp.services.ProcessoServiceRemote;
import br.com.sgp.util.handling.ErrorHandlingAjaxButton;
import br.com.sgp.util.handling.ErrorHandlingForm;
import br.com.ufpr.sgp.components.CustomAutocompletePanel;
import br.com.ufpr.sgp.enums.StatusProcesso;
import br.com.ufpr.sgp.enums.TipoProjeto;
import br.com.ufpr.util.base.BasePage;
import br.com.ufpr.util.base.Protected;

@Protected
@MountPath("CadastrarProcesso")
public class CadastrarProcessoPage extends BasePage {
	private static final long serialVersionUID = -5153294473019230089L;

	@EJB(name = "ClienteServiceImpl")
	private ClienteServiceRemote clienteServiceRemote;
	
	@EJB(name = "ProcessoServiceImpl")
	private ProcessoServiceRemote processoServiceRemote;

	// @Inject
	// private UsuarioService usuarioService;
	//
	// @Inject
	// private RepositorioService repositorioService;
	//
	// @Inject
	// private SmpService smpService;
	//
	// @Inject
	// private RelatorioSMP relatorioSMP;
	//
	// @Inject
	// private StatusService statusService;

	public CadastrarProcessoPage(final ModalCadastrarProcesso modalCadastrarProcesso, final IModel<Processo> processoModel,
	        final PageReference pageReference) {
		super();

		if (inclusao(processoModel)) {
			processoModel.getObject().setTipo(TipoProjeto.REGULARIZACAO.getCodigo());
			processoModel.getObject().setStatus(StatusProcesso.AGUARDANDO_APROVACAO.getCodigo());
		}

		// final ModalScriptSmp modalScriptSmp = new ModalScriptSmp("modalScriptSmp", processoModel);
		// add(modalScriptSmp);

		final ErrorHandlingForm<Processo> processoForm = new ErrorHandlingForm<Processo>("manterProcessoForm",
		        new CompoundPropertyModel<Processo>(processoModel));
		processoForm.add(new TextField<Long>("codigo") {
			private static final long serialVersionUID = -3993502012822324249L;

			@Override
			public boolean isEnabled() {
				return false;
			}

			@Override
			public boolean isVisible() {
				return alteracao(processoModel);
			}
		}.setLabel(new ResourceModel("consultarProcesso.codigo")));


		final DropDownChoice<StatusProcesso> status = new DropDownChoice<StatusProcesso>("status", new Model<StatusProcesso>(StatusProcesso.ESTUDO), Arrays.asList(StatusProcesso.values()));
		
		status.setLabel(new ResourceModel("consultarProcesso.status"));
		status.setEnabled(true);
		processoForm.add(status);

		processoForm.add(new TextArea<String>("descricao").setLabel(new ResourceModel("cadastrarProcesso.descricao")).setRequired(true)
		        .setEnabled(true));
		
//		final AutoCompleteTextField<String> acCliente = new AutoCompleteTextField<String>("acCliente", new Model<String>("")) {
//            private static final long serialVersionUID = 6173052952006948518L;
//
//			@Override
//            protected Iterator<String> getChoices(String input) {
//				if (Strings.isEmpty(input))
//                {
//                    List<String> emptyList = Collections.emptyList();
//                    return emptyList.iterator();
//                }
//
//                List<String> choices = new ArrayList<String>(10);
//
//                Locale[] locales = Locale.getAvailableLocales();
//
//                for (final Locale locale : locales)
//                {
//                    final String country = locale.getDisplayCountry();
//
//                    if (country.toUpperCase().startsWith(input.toUpperCase()))
//                    {
//                        choices.add(country);
//                        if (choices.size() == 10)
//                        {
//                            break;
//                        }
//                    }
//                }
//                return choices.iterator();
//            }
//        };
//        if (alteracao(processoModel)) {
//        	acCliente.setModel(new Model<String>(processoModel.getObject().getCliente().getNome()));
//        }
		
//		AutoCompleteTextField<String> acCliente = new AutoCompleteTextField<String>("acCliente", new PropertyModel<String>(processoForm, "")) {
//			private static final long serialVersionUID = 5030997203375266246L;
//
//			@Override
//			protected Iterator<String> getChoices(String input) {
//				if (!Strings.isEmpty(input)) {
//					List<String> nomes = clienteServiceRemote.autoComplete(input);
//					return nomes.iterator();
//				}
//				return null;
//			}
//		};
//		processoForm.add(acCliente);

		final CustomAutocompletePanel<Cliente> acCliente = new CustomAutocompletePanel<Cliente>("acCliente", new PropertyModel<Cliente>(
		        processoModel, "cliente"), Cliente.class, clienteServiceRemote);
		acCliente.getAutoCompleteTextField().setLabel(new ResourceModel("cadastrarSMP.testador"));
		acCliente.getAutoCompleteTextField().setRequired(true);
		acCliente.getAutoCompleteTextField().add(new AttributeModifier("placeholder", "Login do testador para ser incluído na SMP"));
		processoForm.add(acCliente);


		add(processoForm);

		processoForm.add(new ErrorHandlingAjaxButton("btnVoltar") {
			private static final long serialVersionUID = -883799730060392805L;

			@Override
			protected void onSubmitted(AjaxRequestTarget target) {
				if (modalCadastrarProcesso != null) {
					modalCadastrarProcesso.close(target);

				} else {
					target.appendJavaScript("window.history.back();");
				}
			}

		}.setDefaultFormProcessing(false));

		processoForm.add(new ErrorHandlingAjaxButton("btnSalvar") {
			private static final long serialVersionUID = 6787253824723028584L;

			@Override
			protected void onSubmitted(AjaxRequestTarget target) {
				final boolean inclusao = inclusao(processoModel);
				setUsuarioLogadoDto(processoModel);
				System.out.println(((Processo)processoModel.getObject()).getDescricao());
				Processo processo = (Processo)processoModel.getObject();
				processoServiceRemote.salvarOuAtualizar(processo);;
//				smpService.salvarOuAtualizar(processoModel.getObject());
//				if (pageReference != null && pageReference.getPage() instanceof IReceiveFeedbackPage) {
//					final IReceiveFeedbackPage irfp = (IReceiveFeedbackPage) pageReference.getPage();
//					if (inclusao) {
//						irfp.setFeedbackMessage(
//						        new Model<String>(CustomStringUtils.replace(new ResourceModel("cadastrarSMP.insert.success").getObject(),
//						                new String[] { String.valueOf(processoModel.getObject().getId()) })), target);
//
//					} else {
//						irfp.setFeedbackMessage(new ResourceModel("cadastrarSMP.update.success"), target);
//					}
//				}
			}

			@Override
			protected void onSucess(AjaxRequestTarget target) {
				if (modalCadastrarProcesso != null) {
					modalCadastrarProcesso.close(target);

				} else {
					target.appendJavaScript("window.history.back();");
				}
			}

			@Override
			public boolean isVisible() {
				return true;
			}

		});


	}

}
